import React, { FC, memo, ReactElement, useCallback, useRef, useState } from 'react'

import style from './index.scss'

const tabMenuDatas = [
  {
    type: 'top',
    title: '头条',
  },
  {
    type: 'shehui',
    title: '社会',
  },
  {
    type: 'guonei',
    title: '国内',
  },
  {
    type: 'guoji',
    title: '国际',
  },
  {
    type: 'yule',
    title: '娱乐',
  },
  {
    type: 'tiyu',
    title: '体育',
  },
  {
    type: 'junshi',
    title: '军事',
  },
  {
    type: 'keji',
    title: '科技',
  },
  {
    type: 'caijing',
    title: '财经',
  },
  {
    type: 'shishang',
    title: '时尚',
  },
]

interface IProps {
  changeSearch: (search: string) => void
}

const TabMenu: FC<IProps> = ({ changeSearch }): ReactElement => {
  const [activeNewsType, setActiveNewsType] = useState<string>('top')
  console.log('tabMenu render')
  const preActiveNewsType = useRef<string>(activeNewsType)
  const handleClick = useCallback(
    (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
      const { type } = (e.target as HTMLDivElement).dataset
      if (type) {
        if (type !== preActiveNewsType.current) {
          changeSearch(type)
          setActiveNewsType(type)
          preActiveNewsType.current = type
        }
      }
    },
    [changeSearch, setActiveNewsType],
  )

  return (
    <div className={style['tab-menu']}>
      <div className={style['scroll']}>
        <div className={style['tab-menu-wrapper']} onClick={handleClick}>
          {tabMenuDatas &&
            tabMenuDatas.map((item) => (
              <div
                key={item.title}
                data-type={item.type}
                className={`${style['item']} ${item.type === activeNewsType ? style['active'] : ''}`}
              >
                {item.title}
              </div>
            ))}
        </div>
      </div>
    </div>
  )
}

export default memo(TabMenu)
